import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { Button, Table, Tooltip, Popconfirm } from "antd";
import type { ColumnsType } from "antd/es/table";
import { EyeOutlined, DeleteOutlined } from "@ant-design/icons";
import { observer } from "Mobx-react";
import * as Excel from "exceljs";
import { saveAs } from "file-saver";
import { surveyStore } from "@/stores/survey";
import { processAnswerData } from "@/computed/api";
import type { surveyAnswerType, answerType } from "@/types/index";
import { answerErasure } from "@/computed/answer";
import Screen from "../components/Screen";
import { AnswerCard } from "../stye";

function Answer() {
  const [loading, setLoading] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);
  const [answerData, setAnswerData] = useState<surveyAnswerType[]>([]);
  const [excleData, setExcleData] = useState<string[][]>([]);
  const [exeleQuestion, setExeleQuestion] = useState<string[][]>([]);
  const [dateList, setDate] = useState(["", ""]);
  const [conditionData, setCondition] = useState("and");
  const [screenAnswerData, setScreenAnswer] = useState<answerType[]>([]);

  const columns: ColumnsType<surveyAnswerType> = [
    {
      title: "答卷编号",
      dataIndex: "answerId",
      align: "center"
    },
    {
      title: "开始时间",
      dataIndex: "startTime",
      align: "center"
    },
    {
      title: "结束时间",
      dataIndex: "endTime",
      align: "center"
    },
    {
      title: "答题用时",
      dataIndex: "consumTime",
      align: "center"
    },
    {
      title: "操作",
      dataIndex: "answerId",
      align: "center",
      render: (_, record) => (
        <div className="record-operate">
          <Tooltip title="查看详情">
            <Link target="_blank" className="eye" to={`/question?id=${record.surveyId}&answerId=${record.answerId}`}>
              <EyeOutlined></EyeOutlined>
            </Link>
          </Tooltip>
          <Tooltip title="删除答卷">
            <Popconfirm title="是否删除答卷？" okText="是" cancelText="否" onConfirm={() => courseDelete(record.surveyId, record.answerId)}>
              <DeleteOutlined className="delete" />
            </Popconfirm>
          </Tooltip>
        </div>
      )
    }
  ];

  const getData = async (screenDate: string[], condition: string, screenAnswer: answerType[]) => {
    setLoading(true);
    let { answer, excleList, questionList } = await processAnswerData(surveyStore.surveyId, screenDate, condition, screenAnswer);
    setAnswerData(answer);
    setExcleData(excleList);
    setExeleQuestion(questionList);
    setLoading(false);
  };

  useEffect(() => {
    setCondition("and");
    setScreenAnswer([]);
    getData(dateList, "and", []);
  }, [surveyStore.surveyId]);
  //赛选
  const onScreenQuery = async (screenDate: string[], condition: string, screenAnswer: answerType[]) => {
    setDate(screenDate);
    setCondition(condition);
    setScreenAnswer(screenAnswer);
    await getData(screenDate, condition, screenAnswer);
  };
  //删除
  const courseDelete = async (id: string, answerId?: string) => {
    answerErasure(id, answerId);
    await getData(dateList, conditionData, screenAnswerData);
  };
  //下载答案
  const download = () => {
    setExportLoading(true);
    const workbook = new Excel.Workbook();
    //数据详情
    const sheet = workbook.addWorksheet("数据详情");
    sheet.addRows(excleData);
    sheet.eachRow(row => {
      //修改行
      row.eachCell((cell, colNumber) => {
        cell.border = {
          top: { style: "thin" },
          left: { style: "thin" },
          bottom: { style: "thin" },
          right: { style: "thin" }
        };
        sheet.getColumn(colNumber).width = 20; // 设置列宽
        cell.alignment = { horizontal: "center" }; // 居中
      });
    });
    //题目列表
    const sheet2 = workbook.addWorksheet("题目列表");
    sheet2.addRows(exeleQuestion);
    sheet2.eachRow(row => {
      //修改行
      row.eachCell((cell, colNumber) => {
        cell.border = {
          top: { style: "thin" },
          left: { style: "thin" },
          bottom: { style: "thin" },
          right: { style: "thin" }
        };
        if (colNumber === 1) {
          sheet2.getColumn(colNumber).width = 10;
        } else if (colNumber === 2) {
          sheet2.getColumn(colNumber).width = 40;
        } else if (colNumber === 3) {
          sheet2.getColumn(colNumber).width = 15;
        } else {
          sheet2.getColumn(colNumber).width = 30;
        }

        cell.alignment = { horizontal: "center" }; // 居中
      });
    });
    // 导出文档
    workbook.xlsx.writeBuffer().then(buffer => {
      const data = new Blob([buffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"
      });
      saveAs(data, answerData[0].surveyTitle + ".xlsx");
      setExportLoading(false);
    });
  };
  return (
    <AnswerCard>
      <Screen onScreenQuery={onScreenQuery}></Screen>
      <div className="answer-operate flex-between">
        <span>问卷答案</span>
        {answerData.length !== 0 && (
          <Button type="primary" loading={exportLoading} onClick={download}>
            下载答案数据
          </Button>
        )}
      </div>
      <Table dataSource={answerData} columns={columns} loading={loading} pagination={answerData.length <= 10 ? false : { pageSize: 10 }} rowKey="answerId" bordered></Table>
    </AnswerCard>
  );
}
export default observer(Answer);
